#include "herbselecteddialog.h"
#include "ui_herbselecteddialog.h"
#include <QListWidgetItem>
#include <QPixmap>

HerbSelectedDialog::HerbSelectedDialog(const QHash<QString, Herb>& herbs, QWidget *parent)
    : QDialog(parent), ui(new Ui::HerbSelectedDialog), m_herbs(herbs),m_selectedHerb("") {
    ui->setupUi(this);
    ui->HerbsList->setIconSize(QSize(90, 90)); // 统一图标尺寸
    ui->HerbsList->setSpacing(4);

    // 填充药材列表
    populateHerbsList();

    connect(ui->HerbsList, &QListWidget::itemClicked,
            this, &HerbSelectedDialog::handleItemClicked);
}

void HerbSelectedDialog::populateHerbsList()
{
    ui->HerbsList->clear();

    QListWidgetItem* noneItem = new QListWidgetItem("无");
    noneItem->setData(Qt::UserRole, "");
    noneItem->setIcon(QIcon(":/icons/images/blank.png"));
    ui->HerbsList->addItem(noneItem);


    // 遍历药材数据库
    for (auto it = m_herbs.constBegin(); it != m_herbs.constEnd(); ++it) {
        const QString& herbName = it.key();
        const Herb& herb = it.value();

        // 创建列表项
        QListWidgetItem* item = new QListWidgetItem;

        // 设置显示内容
        item->setText(herbName);
        item->setData(Qt::UserRole, herbName); // 存储药材名称

        // 加载并设置图标
        QPixmap pixmap(herb.iconPath());
        if (!pixmap.isNull()) {
            item->setIcon(QIcon(pixmap.scaled(48, 48, Qt::KeepAspectRatio)));
        } else {
            item->setIcon(QIcon(":/icons/default_herb.png")); // 备用图标
        }

        // 添加至列表
        ui->HerbsList->addItem(item);
    }
}

void HerbSelectedDialog::handleItemClicked(QListWidgetItem *item) {
    m_selectedHerb = item->data(Qt::UserRole).toString();
    accept(); // 自动关闭对话框
}


QString HerbSelectedDialog::selectedHerb() const
{
    return m_selectedHerb;
}

HerbSelectedDialog::~HerbSelectedDialog() {
    delete ui;
}
